/**
 * @author: Phu Ta Script for all request actions in app
 */
var globalContacts = null; // cache
var newGlobalContacts = null;
var globalContactsVarName = "globalContacts";
var newGlobalContactsVarName = "newGlobalContacts";

jQuery.ajaxSetup({ cache: false });
function loadContacts(isSearch, page) {
	//
	$('#div-tbl-content').html("<div class='loading'></div>");
	clearDetailPanel();
	//
	var url = "listContacts.do";
	var searchStr = $("#searchkey").val();
	if(isSearch == true && searchStr != ""){
		url = "searchContact.do";
	}
	var request = $.ajax({
		url : url,
		type : "POST",
		data : {
			searchkey : searchStr,
			page : page
		},
		dataType : "json"
	});
	request.done(function(dataPaging) {
		globalContacts = dataPaging.contactList;
		var table = $("<table></table>");
		$.each(globalContacts, function(i, data) {
			var rowclass = "tbl-content-row";
			if (i % 2 != 0) {
				rowclass = "tbl-content-row-odd";
			}
			var row = $("<tr></tr>").addClass(rowclass).attr("id","r"+i);
			row.attr("onclick", "showContactDetails($(this)," + i + ")");
			var col1 = $("<td></td>").addClass("tbl-content-col").text(
					data.firstName);
			var col2 = $("<td></td>").addClass("tbl-content-col").text(
					data.lastName);
			var col3 = $("<td></td>").addClass("tbl-content-col")
					.text(data.dob);
			row.append(col1);
			row.append(col2);
			row.append(col3);
			table.append(row);
		});
		if(globalContacts.length > 0){
			if(dataPaging.totalPages>1){
				var row = $("<tr></tr>");
				var col = $("<td style='padding-left:5px'></td>").attr("colspan", "3").text("Page: ");
				for(var p = 1; p<=dataPaging.totalPages; p++){
					if(p!=dataPaging.currentPage){
						var num = $("<a class='paging_number'></a>").attr("onclick","loadContacts(false,"+p+")").text(p);
						col.append(num);
					}else{
						var num = $("<a class='paging_number_current'></a>").attr("onclick","loadContacts(false,"+p+")").text(p);
						col.append(num);
					}
				}
				row.append(col);
				table.append(row);
			}
			$('#div-tbl-content').html(table);
		}else{
			$('#div-tbl-content').html("<div class='noresult'>No Results Found.</div>");
		}
		
	});
	request.error(function(err) {
		$('#div-tbl-content').html("<div class='noresult'>An error occurred. Please reload page!</div>");
	})
}
//

function showContactDetails(eventObj, id) {
	if (globalContacts != null) {
		$(".tbl-content-row-selected").removeClass("tbl-content-row-selected");
		if(eventObj != null){
			eventObj.addClass("tbl-content-row-selected");
		}
		var data = globalContacts[id];
		var table = $('<table></table>');
		table.append(buildDetailRow("First Name: ", data.firstName));
		table.append(buildDetailRow("Last Name: ", data.lastName));
		table.append(buildDetailRow("Birthday: ", data.dob));
		table.append(buildDetailRow("Gender: ", data.gender == true ? "Male" : "Female"));
		buildList(data.addresses, "Address", "address", table);
		buildList(data.emails, "Email", "email", table);
		buildList(data.phones, "Phone", "phone", table);

		$("#detail-body").html(table);
		$("#detail-header").html(data.firstName + " "+ data.lastName);
		var footer = "<div class='button-list'><button onclick=\"showEditContactDetails("+id+",'')\" class='stdbut'>Edit</button></div>";
		footer += "<div class='button-list'><button onclick='deleteContact("+id+")' class='stdbut'>Delete</button></div>";
		$("#detail-footer").html(footer);
		$("#detail-footer").append("<div id='action-message'></div>");
	}
}
//
function buildList(data, label, path, table){
	$.each(data, function(i, data) {
		if(data["remove"] == false){
			if(i == 0){
				table.append(buildDetailRow(label+ ": ", data[path]));
			}else{
				table.append(buildDetailRow(label + " "+ i +": ", data[path]));
			}
		}
	});
}
// id: contact id in globalcache
// data: array obj
// path: label for getting value in array
// table: table for display result
function buildInputList(globalContactsVarName, id, data, label, arrayPath, path, table){
	$.each(data, function(i, data) {
		if(data["remove"] == false){
			if(i == 0){
				table.append(buildInputDetailRowForMulti(globalContactsVarName, id, label+ ": ", arrayPath, path, data[path], i));
			}else{
				table.append(buildInputDetailRowForMulti(globalContactsVarName, id, label + " "+ i +": ", arrayPath, path, data[path], i));
			}
		}
	});
	table.append(buildAddInputControl(globalContactsVarName, id, label, arrayPath, path));
}
//
function buildDetailRow(label, value){
	var row = $('<tr></tr>');
	var col1 = $('<td></td>').text(label);
	var col2 = $('<td></td>').addClass('value-text').text(value);
	row.append(col1);
	row.append(col2);
	return row;
}
// add more
function buildAddInputControl(globalContactsVarName, id, label, arrayPath, path){
	var row = $('<tr></tr>');
	var col1 = $('<td></td>');
	var col2 = $('<td></td>');
	var col3 = $('<td></td>');
	var add = $('<a></a>').text('+ Add '+label).attr({
		onclick:'addNewInputRow($(this),1,\''+globalContactsVarName+'\','+globalContactsVarName+','+id+',\''+label+'\',\''+arrayPath+'\',\''+path+'\')',
	}).addClass('add');
	col2.append(add);
	row.append(col1);
	row.append(col2);
	row.append(col3);
	return row;
}
function addNewInputRow(eventObj, level, globalContactsVarName, globalContactsRef, id, label, arrayPath, path){
	var item = {};
	item[path] = "";
	item['remove'] = false;
	var data = globalContactsRef[id];
	data[arrayPath].push(item);
	var idlv2 = data[arrayPath].length - 1;
	var uniqueID = path+idlv2;
	var row = $("<tr></tr>");
	var col1 = $("<td></td>").addClass('value-text').text(label + ' ' + (idlv2) + ': ');
	var col2 = $("<td></td>");
	var col3 = $("<td></td>");
	var input = $("<input/>").attr({
	    name:path,
	    type:'text',
	    onchange:'updateExistContactCacheValue($(this),'+globalContactsVarName+','+id+',\''+arrayPath+'\',\''+path+'\',$(this).val(),'+idlv2+')',
	}).addClass('input-control');
	var remove = $('<a></a>').text('Remove').attr({
		onclick:'removeInputRow($(this),1);updateExistContactCacheValue($(this),'+globalContactsVarName+','+id+',\''+arrayPath+'\',\'remove\',true,'+idlv2+')',
	}).addClass('remove');
	//
	var validation = "<div class='validate'></div>";
	//
	col2.append(input);col2.append(validation);
	col3.append(remove);
	row.append(col1);
	row.append(col2);
	row.append(col3);
	eventObj.parents().eq(level).before(row);
}
//
function buildInputDetailRow(globalContactsVarName, id, label, arrayPath, path, value, idlv2){
	var row = $("<tr></tr>");
	var col1 = $("<td></td>").addClass("value-text").text(label);
	var col2 = $("<td></td>");
	var col3 = $("<td><div class='validate'></div></td>");
	var input = $("<input/>").attr({
	    value:value, 
	    name:path,
	    type:'text',
	    onchange:'updateExistContactCacheValue($(this),'+globalContactsVarName+','+id+',\''+arrayPath+'\',\''+path+'\',$(this).val(),'+idlv2+')',
	}).addClass('input-control');
	//
	col2.append(input);
	row.append(col1);
	row.append(col2);
	row.append(col3);
	return row;
}
//
function buildInputDateDetailRow(globalContactsVarName, id, label, arrayPath, path, value, idlv2){
	var row = $("<tr></tr>");
	var col1 = $("<td></td>").addClass('value-text').text(label);
	var col2 = $("<td></td>");
	var col3 = $("<td><div class='validate'></div></td>");
	var input = $('<input/>').attr({
		id:"datepicker",
	    value:value, 
	    name:path,
	    type:'text',
	    onchange:'updateExistContactCacheValue($(this),'+globalContactsVarName+','+id+',\''+arrayPath+'\',\''+path+'\',$(this).val(),'+idlv2+')',
	}).addClass('input-control');
	//
	col2.append(input);
	row.append(col1);
	row.append(col2);
	row.append(col3);
	return row;
}
//
function buildInputDetailRowForMulti(globalContactsVarName, id, label, arrayPath, path, value, idlv2){
	var row = $("<tr></tr>");
	var col1 = $("<td></td>").addClass("value-text").text(label);
	var col2 = $("<td></td>");
	var col3 = $("<td></td>");
	var uniqueID = path+idlv2;
	var input = $("<input/>").attr({
	    value:value, 
	    name:path,
	    id:uniqueID,
	    type:'text',
	    onchange:'updateExistContactCacheValue($(this),'+globalContactsVarName+','+id+',\''+arrayPath+'\',\''+path+'\',$(this).val(),'+idlv2+')',
	}).addClass('input-control');
	var remove = $('<a></a>').text('Remove').attr({
		onclick:'removeInputRow($(this),1);updateExistContactCacheValue($(this),'+globalContactsVarName+','+id+',\''+arrayPath+'\',\'remove\',true,'+idlv2+')',
	}).addClass('remove');
	//
	var validation = "<div class='validate'></div>";
	//
	col2.append(input);col2.append(validation);
	col3.append(remove);
	row.append(col1);
	row.append(col2);
	row.append(col3);
	return row;
}
function buildRadioDetailRow(globalContactsVarName, id, label, path, labelArray, valueArray, gender, idlv2){
	var row = $('<tr></tr>');
	var col1 = $('<td></td>').addClass('value-text').text(label);
	var col2 = $('<td></td>');
	var col3 = $('<td></td>');
	for(var i = 0; i < labelArray.length; i++ ){
		var input = $('<input/>').attr({
		    name:path,
		    value:valueArray[i],
		    checked:(gender == valueArray[i])?true : false,
		    onchange:'updateExistContactCacheValue($(this),'+globalContactsVarName+','+id+',\'\',\''+path+'\',$(this).val()===\'true\','+idlv2+')',
		    type:'radio'
		});
		var label = $("<label></label>").attr({
			style:"margin-right: 15px"
		}).text(labelArray[i]);
		col2.append(input);
		col2.append(label);
	}
	
	row.append(col1);
	row.append(col2);
	row.append(col3);
	return row;
}
//
function updateExistContactCacheValue(eventObj, globalContactsRef, id, arrayPath, path, value, idlv2){
	// check empty
	if(validateIsEmpty(eventObj, value)){
		return false;
	};
	//
	if(path=="email"){
		if(!validateEmail(eventObj, value)) {
			$("#savebut").css('display','none');
			$("#dissavebut").css('display','block');
			return false;
		}else{
			$("#savebut").css('display','block');
			$("#dissavebut").css('display','none');
		}
	}
	//
	if(path=="phone"){
		if(!validatePhone(eventObj, value)) {
			$("#savebut").css('display','none');
			$("#dissavebut").css('display','block');
			return false;
		}else{
			$("#savebut").css('display','block');
			$("#dissavebut").css('display','none');
		}
	}
	//
	if (globalContactsRef != null) {
		var multiObj = ["emails","addresses","phones"];
		var multiIndex = $.inArray(arrayPath, multiObj);
		if(multiIndex == -1){
			globalContactsRef[id][path] = value;
		}else{
			globalContactsRef[id][arrayPath][idlv2][path] = value;
		}
	}
	$("#action-message").html("");
}
function removeInputRow(currObj, level){
	currObj.parents().eq(level).remove();
}
//
function validateIsEmpty(eventObj, value){
	if(value == "" & value !== false){
		eventObj.parents().eq(1).find(".validate").html("Please enter value!");
		return true;
	}else{
		eventObj.parents().eq(1).find(".validate").html("");
		return false;
	}
}
function validateEmail(eventObj, value){
	var emailRegexStr = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
	var isvalid = emailRegexStr.test(value); 
	if(!isvalid){
		eventObj.parents().eq(1).find(".validate").html("Please enter a valid email address.");
		return false;
	}else{
		return true;
	}
}
function validatePhone(eventObj, value){
	var phoneRegexStr = /^\+?[0-9\.\ ()\+]+$/;
	var isvalid = phoneRegexStr.test(value); 
	if(!isvalid){
		eventObj.parents().eq(1).find(".validate").html("Please enter a valid phone number.");
		return false;
	}else{
		return true;
	}
}
// /
// /
// id: of contact in global cache list
// message: message for saved or not
function showEditContactDetails(id, message) {
	if (globalContacts != null) {
		var data = globalContacts[id];
		var table = $("<table></table>");
		table.append(buildInputDetailRow(globalContactsVarName, id, "First Name: ","","firstName", data.firstName));
		table.append(buildInputDetailRow(globalContactsVarName, id, "Last Name: ","","lastName", data.lastName));
		table.append(buildInputDateDetailRow(globalContactsVarName, id, "Birthday: ","","dob", data.dob));
		table.append(buildRadioDetailRow(globalContactsVarName, id, "Gender: ", "gender", new Array("Male","Female"), new Array(true,false), data.gender, -1));
		buildInputList(globalContactsVarName, id, data.addresses, "Address", "addresses", "address", table);
		buildInputList(globalContactsVarName, id, data.emails, "Email", "emails", "email", table);
		buildInputList(globalContactsVarName, id, data.phones, "Phone", "phones", "phone", table);

		$("#detail-body").html(table);
		$("#detail-header").html(data.firstName + " "+ data.lastName);
		$("#detail-footer").html("<div class='button-list'><button id='savebut' onclick='updateContact("+id+")' class='stdbut'>Save</button>" +
				"<button id='dissavebut' class='stdbut-disable'>Save</button></div>");
		$("#detail-footer").append("<div id='action-message'>"+message+"</div>");
		$( "#datepicker" ).datepicker();
	}
}
// add new contact form
function showAddContactDetailsForm(id) {
	if (newGlobalContacts != null) {
		var data = newGlobalContacts[id];
		var table = $('<table></table>');
		table.append(buildInputDetailRow(newGlobalContactsVarName, id, "First Name: ","","firstName", data.firstName));
		table.append(buildInputDetailRow(newGlobalContactsVarName, id, "Last Name: ","","lastName", data.lastName));
		table.append(buildInputDateDetailRow(newGlobalContactsVarName, id, "Birthday: ","","dob", data.dob));
		table.append(buildRadioDetailRow(newGlobalContactsVarName, id, "Gender: ", "gender", new Array("Male","Female"), new Array(true,false), data.gender, -1));
		buildInputList(newGlobalContactsVarName, id, data.addresses, "Address", "addresses", "address", table);
		buildInputList(newGlobalContactsVarName, id, data.emails, "Email", "emails", "email", table);
		buildInputList(newGlobalContactsVarName, id, data.phones, "Phone", "phones", "phone", table);

		$("#detail-body").html(table);
		$("#detail-header").html("Create New Contact");
		$("#detail-footer").html("<div class='button-list'><button id='savebut' onclick='addContact("+id+")' class='stdbut'>Save</button>" +
				"<button id='dissavebut' class='stdbut-disable'>Save</button></div>");
		$("#detail-footer").append("<div id='action-message'></div>");
		$( "#datepicker" ).datepicker();
	}
}

// new contact obj
function newContactObj(){
	var contact = {};
	contact["firstName"] = "";
	contact["lastName"] = "";
	contact["gender"] = true;
	contact["dob"] = "1990-01-01";
	contact["addresses"] = [];
	contact["emails"] = [];
	contact["phones"] = [];
	return contact;
}
function generateNewContactForm(){
	newGlobalContacts = [];
	newGlobalContacts.push(newContactObj());
	showAddContactDetailsForm(0);
}
//
function clearDetailPanel(){
	$("#detail-body").html("");
	$("#detail-header").html("");
	$("#detail-footer").html("");
}
// update Contact
function updateContact(id){
	// check
	var error = false;
	$("#detail-body input:text").each(function(index) {
		if(validateIsEmpty($( this ), $( this ).val())) error = true;
	});
	if(error){
		return false;
	}
	//
	var contact = globalContacts[id];
	var request = $.ajax({
		url : "updateContact.do",
		type : "POST",
		contentType: 'application/json',
		data : JSON.stringify(contact),
		dataType : "json"
	});
	request.done(function(data) {
		if(data.idContact == contact.idContact){
			globalContacts[id] = data;
			showEditContactDetails(id, "Saved successfully!");
			//
			var col1 = $("<td></td>").addClass("tbl-content-col").text(data.firstName);
			var col2 = $("<td></td>").addClass("tbl-content-col").text(data.lastName);
			var col3 = $("<td></td>").addClass("tbl-content-col").text(data.dob);
			var insideRow = [col1,col2,col3];
			$("#r"+id).html(insideRow);
		}else{
			alert('Error');
		}
	});
	request.error(function(data) {
		alert('An error occurred');
	})
}
// add new contact
function addContact(id){
	if(newGlobalContacts != null){
		// check
		var error = false;
		$("#detail-body input:text").each(function(index) {
			if(validateIsEmpty($( this ), $( this ).val())) error = true;
		});
		if(error){
			return false;
		}
		//
		var contact = newGlobalContacts[id];
		var request = $.ajax({
			url : "addContact.do",
			type : "POST",
			contentType: 'application/json',
			data : JSON.stringify(contact),
			dataType : "html"
		});
		request.done(function(data) {
			if(data == "error"){
				$("#action-message").addClass("red").html("Error! Please try again or contact administrator!");
			}else if(data.length < 255){
				clearDetailPanel();
				loadContacts(false, 1);
				$("#detail-body").html("<div class='detailpanel-message'>Contact has been inserted successfully!</div>");
			}else{
				$("#action-message").addClass("red").html("Authentication error! Please <a href='login'>login</a> again...");
			}
		});
		request.error(function(datas) {
			alert('An error occurred');
		})
	}
}
// delete contact
function deleteContact(id){
	var contact = globalContacts[id];
	var cf=confirm("Are you sure to delete "+contact.firstName+ " " + contact.lastName + "'s contact?");
	if(cf == true){
		var request = $.ajax({
			url : "deleteContact.do",
			type : "POST",
			contentType: 'application/json',
			data : JSON.stringify(contact),
			dataType : "html"
		});
		request.done(function(data) {
			if(data == "error"){
				$("#action-message").addClass("red").html("Error! Can not delete this contact!");
			}else if(data.length < 255){
				clearDetailPanel();
				loadContacts(false, 1);
				$("#detail-body").html("<div class='detailpanel-message'>Contact has been deleted successfully!</div>");
			}else{
				$("#action-message").addClass("red").html("Authentication error! Please <a href='login'>login</a> again...");
			}
		});
		request.error(function(datas) {
			alert('An error occurred');
		})
	}
}
////